require 'socket'

class IrisPoller

  attr_accessor :hosts, :port, :path

  def initialize(hosts=%w[ 192.168.0.95 192.168.0.96 ], port=80, path="/getData.cgi")
    @hosts = hosts
    @port = port
    @path = path
  end

  def poll_hosts
    data_points = Array.new

    @hosts.each { |host|
      request = "GET #{@path} HTTP/1.0\r\n\r\n"
      socket = TCPSocket.open(host, @port)

      socket.print(request)

      parse_data(host, socket.read).each { |data_point|
        data_points.push(data_point)
      }
    }
    return data_points
  end

  def parse_data(address, data)
    data_points = Array.new

    data.split("<").each { |line|
      if line.include? "time="
        point = line.chomp.delete("/>").split("\n")[0]
        attributes = point.split(" ")

        id = attributes[0].split("cfg")[1]
        value = attributes[1].split("value=")[1].delete("\"")
        date = attributes[2].split("date=")[1].delete("\"")
        time = attributes[3].split("time=")[1].delete("\"").split(".")[0]

        addr = address.split(".")[3]
        datetime = date + " " + time

        data_points.push([addr, id, value, datetime])
      end
    }
    return data_points
  end

end

# example usage
# ip = IrisPoller.new
# data = ip.poll_hosts
